package com.toogu.mazhangmen.util;

import android.os.Message;

import com.basic.G;
import com.lib.EDEV_ATTR;
import com.lib.EUIMSG;
import com.lib.FunSDK;
import com.lib.IFunSDKResult;
import com.lib.MsgContent;
import com.lib.sdk.bean.alarm.AlarmInfo;
import com.toogu.mazhangmen.bean.EquipmentsBean;

import java.util.HashMap;

public class AlarmUtil implements IFunSDKResult {
    private static final String TAG = "AlarmUtil";
    private volatile static AlarmUtil alarmUtil;
    private static int mUserId = -1;

    private HashMap<String,Boolean> hashMap;

    public static AlarmUtil getInstance() {
        if (alarmUtil == null) {
            synchronized (OkhttpUtil.class) {
                if (alarmUtil == null) {
                    alarmUtil = new AlarmUtil();
                }
            }
        }
        return alarmUtil;
    }
    private AlarmUtil(){
        // 注册一个User操作句柄
        mUserId = FunSDK.RegUser(this);
        // 设置局域网报警消息监听,如果是多个设备,也只需要设置一次即可,所有设备报警都在此返回
        FunSDK.DevSetAlarmListener(mUserId, 0);
        hashMap=new HashMap<>();
    }

    public boolean setLanAlarm(EquipmentsBean equipmentsBean, boolean enable) {
        int nValue = enable ? 1 : 0;	// 0为关闭 ，非0为开启（建议赋1）
        //todo 模板里面只有这个接口，调用以后返回参数不是1 就失败了。
        int result = FunSDK.DevSetAttrAlarmByInt(mUserId, equipmentsBean.getCode(), EDEV_ATTR.EDA_OPT_ALARM, nValue, 0);
        if(result==1) {
            hashMap.put(equipmentsBean.getCode(),enable);
        }
        return (result == 1);
    }

    public boolean isAlarm(String devId){
        if(hashMap.containsKey(devId)) return hashMap.get(devId);
        return false;
    }

    @Override
    public int OnFunSDKResult(Message msg, MsgContent msgContent) {
        switch(msg.what) {
            case EUIMSG.DEV_LOGIN:
            break;
            case EUIMSG.DEV_SET_ATTR:
            break;
            case EUIMSG.DEV_GET_LAN_ALARM: {
                // 收到局域网报警消息
                // 设备的序列号
                String devId = msgContent.str;
                String dumpStr = devId;
                try {
                    String json = G.ToString(msgContent.pData);
                    AlarmInfo alarmInfo = new AlarmInfo();
                    alarmInfo.onParse(json);
                    dumpStr += " | " + alarmInfo.getStartTime() + " | " + alarmInfo.getEvent();
                    ToastUtil.getToastUtil().add(dumpStr);
                } catch ( Exception e ) {
                    e.printStackTrace();
                }
                hashMap.put(devId,true);
            }
            break;
        }
        return 0;
    }


}
